package com.geek.projects.user.web;

import com.geek.projects.user.service.UserService;
import com.geek.projects.user.service.impl.UserServiceImpl;
import com.geek.projects.utils.HttpServletRequestUtil;
import com.geek.web.mvc.controller.PageController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;


/**
 * @author lizhiyang
 */
@Path("/user")
public class LoginController implements PageController {

    private final UserService userService = new UserServiceImpl();

    @GET
    @Path("/login/form")
    public String loginForm(HttpServletRequest request, HttpServletResponse response) {
        return "login-form.jsp";
    }

    @POST
    @Path("/login")
    public String login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        //获取参数
        Map<String, Object> params = HttpServletRequestUtil.getParams(request);
        try {
            userService.login(params);
            return "login-success.jsp";
        } catch (Exception e) {
            writer.println(e.getMessage());
            writer.flush();
            return null;
        }

    }


    @GET
    @Path("/register/form")
    public String registerForm(HttpServletRequest request, HttpServletResponse response) {
        return "register-form.jsp";
    }

    @POST
    @Path("/register")
    public String register(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        //获取参数
        Map<String, Object> params = HttpServletRequestUtil.getParams(request);
        try {
            userService.register(params);
            return "register-success.jsp";
        } catch (Exception e) {
            writer.println(e.getMessage());
            writer.flush();
            return null;
        }

    }
}
